package com.ddone.util.mock;

import com.google.common.base.CaseFormat;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ddone
 * @date 2024/5/15-09:50
 */
public class MapUtil {
    public static <K, T> Map<K, T> getMapFromList(List<T> list, String keyName) {
        Map<K, T> map = new HashMap<>();
        try {
            for (T entity : list) {
                String keyNameUp = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, keyName);
                Method method = entity.getClass().getDeclaredMethod("get" + keyNameUp, new Class[0]);
                K key = (K)method.invoke(entity, new Object[0]);
                map.put(key, entity);
            }
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("can't get id from the entity");
        }
    }

    public static <T> Map<Long, T> getIdMapFromList(List<T> list, String keyName) {
        Map<Long, T> map = new HashMap<>();
        try {
            for (T entity : list) {
                String keyNameUp = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, keyName);
                Method method = entity.getClass().getDeclaredMethod("get" + keyNameUp, new Class[0]);
                Long key = (Long)method.invoke(entity, new Object[0]);
                map.put(key, entity);
            }
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("can't get id from the entity");
        }
    }
}